/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect } from 'react';
import { Form, Button, message } from 'antd';
import { approveTemplate, getTemplateAuditList } from '@/services/templateAudit';
import { formatFormValue, formatTemApproveParams, TemApproveCoulmns } from './utils';
import TemRejectModal from './common/TemRejectModal';
import TemCommonTable from './common/TemCommonTable';
import type { CommonIndexType } from '../types/Common';
import TemCommonForm from './common/TemCommonForm';

const TemApprove = (props: CommonIndexType) => {
  const { screenSize, pageKey, show } = props;
  const [form] = Form.useForm();
  const [dataList, setDataList] = useState([]);
  const [pagination, setPagination] = useState({});
  const [modalProps, setModalProps] = useState({});

  const onFinish = async ({ current }: any) => {
    const formValue = formatFormValue(form.getFieldsValue());
    const { dataList: list, pagination: paginationParams } = await getTemplateAuditList({
      page_num: current || 1,
      part: pageKey,
      state: 'approved',
      ...formValue,
    });
    setDataList(list);
    setPagination({ ...paginationParams });
  };

  useEffect(() => {
    if (show) {
      onFinish({});
    }
  }, [show]);

  const onOperation = async (ids: any) => {
    setModalProps({
      ids,
      visible: true,
    });
  };

  const onCloseModal = () => {
    setModalProps({
      visible: false,
    });
  };
  const onHandleModal = async (params: any) => {
    const { ids, reason } = params;
    onCloseModal();
    const { result } = await approveTemplate({
      state: 'approved2reject',
      reject_reason: reason,
      ...formatTemApproveParams([ids]),
    });
    if (result) {
      message.info('操作成功');
      onFinish(pagination);
    }
  };

  const oparateCoumn = {
    title: '操作',
    dataIndex: 'user',
    render: (_: any, record: any) => <Button onClick={onOperation.bind(null, record)}>拒绝</Button>,
  };

  return (
    <>
      <TemCommonForm onFinish={onFinish} screenSize={screenSize} form={form} isShowDate />
      <TemCommonTable
        rowKey='ssid'
        columns={[...TemApproveCoulmns, oparateCoumn]}
        dataSource={dataList}
        onChange={onFinish}
        pagination={pagination}
      />
      <TemRejectModal
        title='请选择拒绝原因'
        onok={onHandleModal}
        onCancel={onCloseModal}
        {...modalProps}
      />
    </>
  );
};

export default TemApprove;
